package com.runachina.common;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.runachina.R;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

public class RudeRunaModbusActivity extends BaseActivity {

    private EditText uartrate, uartcheck, uartdata, uartstop;
    private Button setbtn;
    private TextView uarttext;

    private TextView readpwr, endTime;
    public static TextView pwr;

    private TextView tv_version_name;


    public static byte[] read_pwr = {0x68, 0x32, 0x00, 0x32, 0x00, 0x68, 0x4b,
            (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
            0x02, 0x0C, (byte) 0x71, 0x00, 0x00, 0x01, 0x00,
            (byte) 0xC7, 0x16,
            0x00, 0x16};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_runamodbusrude);

        set_toolbar("调试工具", "");

        set_leftmenu3(RudeRunaModbusActivity.this);

        init_view();

        getUartData();

        inWhichAc = "runa.RudeRunaModbusActivity";

        readpwr.performClick();
    }

    /**
     * 初始化界面控件
     */
    void init_view() {
        uartrate = (EditText) findViewById(R.id.uartrate);
        uartcheck = (EditText) findViewById(R.id.uartcheck);
        uartdata = (EditText) findViewById(R.id.uartdata);
        uartstop = (EditText) findViewById(R.id.uartstop);
        tv_version_name= (TextView) findViewById(R.id.tv_version_name);
        setbtn = (Button) findViewById(R.id.setbtn);
        setbtn.setOnClickListener(setbtnFun);

        uarttext = (TextView) findViewById(R.id.uarttext);

        readpwr = (TextView) findViewById(R.id.readpwr);
        readpwr.setOnClickListener(readpwrFun);
        pwr = (TextView) findViewById(R.id.pwr);

        endTime = (TextView) findViewById(R.id.endTime);
        String endTimeStr = "" + readLocalCfg("endTimeCfg");
        endTime.setText(endTimeStr);
        tv_version_name.setText(getVersion());
    }


    OnClickListener readpwrFun = new OnClickListener() {
        @Override
        public void onClick(View v) {

            inWhichAc = "common.RudeRunaModbusActivity.readpwr";
            pwr.setText("??%");
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(read_pwr);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    TcpSocket.receServerMessage();
//                }
//            }, 3000);
        }
    };

    OnClickListener setbtnFun = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int uartValue = setUartData();
            if (uartValue != -1) {
                SendDataAnalysis.transmit[19] = (byte) uartValue;
                getUartData();
                Toast.makeText(RudeRunaModbusActivity.this, "设置成功!", Toast.LENGTH_SHORT).show();
            } else {
                uarttext.setText("串口参数错误!");
            }
        }
    };

    /**
     * 获取当前串口设置
     *
     * @return
     */
    private int setUartData() {

        int Value = 0;//Value是串口值
        String rateStr = uartrate.getText().toString();
        switch (rateStr) {
            case "300":
                Value = Value | (0x00 << 5);
                break;
            case "600":
                Value = Value | (0x01 << 5);
                break;
            case "1200":
                Value = Value | (0x02 << 5);
                break;
            case "2400":
                Value = Value | (0x03 << 5);
                break;
            case "4800":
                Value = Value | (0x04 << 5);
                break;
            case "7200":
                Value = Value | (0x05 << 5);
                break;
            case "9600":
                Value = Value | (0x06 << 5);
                break;
            case "19200":
                Value = Value | (0x07 << 5);
                break;
            default:
                Value = -1;
                break;
        }

        String checkStr = uartcheck.getText().toString();
        switch (checkStr) {
            case "0":
                Value = Value | (0x00 << 2);
                break;
            case "1":
                Value = Value | (0x02 << 2);
                break;
            case "2":
                Value = Value | (0x03 << 2);
                break;
            default:
                Value = -1;
                break;
        }
        String dataStr = uartdata.getText().toString();
        switch (dataStr) {
            case "5":
                Value = Value | 0x00;
                break;
            case "6":
                Value = Value | 0x01;
                break;
            case "7":
                Value = Value | 0x02;
                break;
            case "8":
                Value = Value | 0x03;
                break;
            default:
                Value = -1;
                break;
        }
        String stopStr = uartstop.getText().toString();
        switch (stopStr) {
            case "1":
                Value = Value | (0x00 << 4);
                break;
            case "2":
                Value = Value | (0x01 << 4);
                break;
            default:
                Value = -1;
                break;
        }
        return Value;
    }


    private void getUartData() {
        /*uart=64;*/
        String uartmsg = "";

        int value = ((int) SendDataAnalysis.transmit[19]) & 0xFF;

        if ((value >> 5) == 0x01) uartmsg = "600 ";
        else if ((value >> 5) == 0x02) uartmsg = "1200 ";
        else if ((value >> 5) == 0x03) uartmsg = "2400 ";
        else if ((value >> 5) == 0x04) uartmsg = "4800 ";
        else if ((value >> 5) == 0x05) uartmsg = "7200 ";
        else if ((value >> 5) == 0x06) uartmsg = "9600 ";
        else if ((value >> 5) == 0x07) uartmsg = "19200 ";
        else if ((value >> 5) == 0x00) uartmsg = "300 ";


        if (((value >> 2) | 252) == 254) uartmsg = uartmsg + "偶校验 ";
        else if (((value >> 2) | 252) == 255) uartmsg = uartmsg + "奇校验 ";
        else if (((value >> 2) | 252) == 252) uartmsg = uartmsg + "无校验 ";


        if ((value | 252) == 253) uartmsg = uartmsg + "数据位6 ";
        else if ((value | 252) == 254) uartmsg = uartmsg + "数据位7 ";
        else if ((value | 252) == 255) uartmsg = uartmsg + "数据位8 ";
        else if ((value | 252) == 252) uartmsg = uartmsg + "数据位5 ";


        if (((value >> 4) | 254) == 255) uartmsg = uartmsg + "停止位2 ";
        else if (((value >> 4) | 254) == 254) uartmsg = uartmsg + "停止位1 ";

        uarttext.setText(uartmsg);
    }

    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     *
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult = TcpSocket.wificonnect();
        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        } else {
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }

    private MenuItem me;
    private int type = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me = item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()) {
            case R.id.menu_connect:
                String connectResult = TcpSocket.wificonnect();//start wifi connect
                show(connectResult);//Toast connect result
                if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                } else {
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            type = 1;
                        }
                    }, 1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(RudeRunaModbusActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                type = 0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (me != null) {
                    if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
                        me.setTitle("connect!");
                        me.setIcon(R.drawable.wifi_connect);
                    } else {
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }
                }
            }
        });
    }

    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
